<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Role;
use App\ModuleModel;

class RoleController extends Controller
{
    //
    public function index()
    {
      // 进入列表页
      $like = '';
      $data = Role::where('deleted_at',null)->orderBy('orderId','asc')->paginate(10);
      return view('roles.index',compact('data','like'));
    }

    public function select(Request $request)
    {
      $like = $request->get('like');
      $data = Role::where('deleted_at',null)->where('position','like','%'.$like.'%')->orderBy('orderId','asc')->paginate(10);
      return view('roles.index',compact('data','like'));
    }

    public function create()
    {
      // 进入添加页
      $modules = ModuleModel::where('deleted_at',null)->get();
      return view('roles.create',compact('modules'));
    }

    public function store(Request $request)
    {
      // 数据存入数据库
      $data = $request->all();
      // 获取当前时间
      // $date = date("Y-m-d H:i:s",time());
      $modules = implode(",",$data['modules']);
      $position = $data['position'];
      $users = Role::create(array_merge($data,[
        'position' => $position,
        'modules' => $modules
      ]));
      return redirect('/roles/index');
    }

    // 进入修改页面
    public function edit($id){
      $data = Role::findOrFail($id);
      $modules = ModuleModel::where('deleted_at',null)->get();
      $module = explode(",",$data->modules);
      return view('roles.edit',compact('data','modules','module'));
    }


    // 执行修改操作
    public function update(Request $request)
    {
        $data = $request->all();
        $modules = implode(",",$data['modules']);
        $position = $data['position'];
        Role::where('id',$data['id'])->update([
          'position' => $data['position'],
          'modules' => $modules,
          'orderId' => $data['orderId']
        ]);
        return redirect('/roles/index');
    }


    // 删除操作
    public function del(Request $request)
    {
      $id = $request->get('id');
      $user = \Auth::user();
      $date = date("Y-m-d H:i:s",time());
      $operation = Role::where('id',$id)->update(['deleted_at' => $date,'deleted_userId' => $user->id]);
      if($operation){
        $data = "删除成功";
      }else{
        $data = "删除失败";
      }

      return response()->json($data);
    }
}
